import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { 
  FileText,
  Clock,
  CheckCircle,
  AlertCircle,
  TrendingUp,
  BarChart3,
  Brain,
  Loader2,
  X
} from 'lucide-react'
import { toast } from 'sonner'
import apiService from '../services/api'
import AIAnalysisDisplay from './AIAnalysisDisplay'
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts'

export default function ReportResults() {
  const [tasks, setTasks] = useState([])
  const [loading, setLoading] = useState(false)
  const [selectedTask, setSelectedTask] = useState(null)
  const [showReportModal, setShowReportModal] = useState(false)
  const [reportLoading, setReportLoading] = useState(false)
  const [reportData, setReportData] = useState(null)
  const [aiAnalysis, setAiAnalysis] = useState('')
  const [aiLoading, setAiLoading] = useState(false)

  // 获取任务列表
  useEffect(() => {
    fetchTasks()
  }, [])

  const fetchTasks = async () => {
    try {
      setLoading(true)
      const response = await apiService.get('/prediction/tasks')
      console.log('API响应:', response)
      
      // 确保 tasks 是一个数组
      const tasksData = response.data?.items || response.data || []
      if (Array.isArray(tasksData)) {
        setTasks(tasksData)
      } else {
        console.error('API响应数据不是数组:', tasksData)
        setTasks([])
        toast.error('任务数据格式错误')
      }
    } catch (error) {
      console.error('获取任务列表失败:', error)
      toast.error('获取任务列表失败')
      setTasks([]) // 确保在错误情况下 tasks 仍然是数组
    } finally {
      setLoading(false)
    }
  }

  // 查看报表
  const handleViewReport = async (task) => {
    try {
      setSelectedTask(task)
      setShowReportModal(true)
      setReportLoading(true)
      setReportData(null)
      setAiAnalysis('')
      setAiLoading(true)

      console.log('开始生成报表，任务ID:', task.id)

      // 获取报表数据
      const reportResponse = await apiService.getReportData(task.id)
      console.log('报表数据获取成功')
      setReportData(reportResponse.data)
      
      // 检查AI分析文件是否存在
      const aiAnalysis = reportResponse.data.aiAnalysis
      if (aiAnalysis && aiAnalysis.exists && aiAnalysis.content) {
        console.log('从文件读取AI分析结果')
        setAiAnalysis(aiAnalysis.content)
        setAiLoading(false)
      } else {
        console.log('AI分析文件不存在，显示生成中提示')
        setAiAnalysis('AI分析生成中，请等待...')
        setAiLoading(false) // 显示提示信息，不显示loading动画
        
        // 可选：在后台触发AI分析生成
        if (reportResponse.data.task && reportResponse.data.task.task_id) {
          console.log('后台触发AI分析生成')
          apiService.getIndustryAnalysis(
            "作为一个行业调研专家，查询下 中国医药行业现状与未来5年发展情况，以及人药制剂（生物药）板块，人药原料，中国农药(植保)板块，动保（兽药）板块 分别的现状与未来5年发展情况，要求 900字 ，使用markdown格式",
            reportResponse.data.task.task_id
          ).then(response => {
            console.log('后台AI分析完成')
            if (response.data && response.data.content) {
              setAiAnalysis(response.data.content)
            }
          }).catch(error => {
            console.error('后台AI分析失败:', error)
            setAiAnalysis('AI分析生成失败，请稍后重试')
          })
        }
      }

      setReportLoading(false)

    } catch (error) {
      console.error('生成报表失败:', error)
      toast.error('生成报表失败')
      setReportLoading(false)
    }
  }

  // 关闭报表
  const handleCloseReport = () => {
    setShowReportModal(false)
    setSelectedTask(null)
    setReportData(null)
    setAiAnalysis('')
    setAiLoading(false)
  }

  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString) return ''
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  }

  // 处理图表数据
  const processChartData = (chartData) => {
    if (!chartData) return { revenueChartData: [], profitChartData: [], profitMarginChartData: [], growthRateChartData: [] }

    const years = chartData.years || []
    const revenueData = chartData.revenue_data || {}
    const profitData = chartData.profit_data || {}
    const profitMarginData = chartData.profit_margin_data || {}
    const growthRateData = chartData.growth_rate_data || {}

    // 收入图表数据
    const revenueChartData = years.map(year => {
      const dataPoint = { year: year.toString() }
      Object.keys(revenueData).forEach(sector => {
        if (revenueData[sector][year] !== undefined) {
          dataPoint[sector] = revenueData[sector][year]
        }
      })
      return dataPoint
    })

    // 净利润图表数据
    const profitChartData = years.map(year => {
      const dataPoint = { year: year.toString() }
      Object.keys(profitData).forEach(sector => {
        if (profitData[sector][year] !== undefined) {
          dataPoint[sector] = profitData[sector][year]
        }
      })
      return dataPoint
    })

    // 净利润率图表数据（只显示历史数据2021-2024）
    const profitMarginChartData = chartData.historical_years?.map(year => {
      const dataPoint = { year: year.toString() }
      Object.keys(profitMarginData).forEach(sector => {
        if (profitMarginData[sector][year] !== undefined) {
          dataPoint[sector] = profitMarginData[sector][year]
        }
      })
      return dataPoint
    }) || []

    // 综合增长率图表数据（只显示预测年份）
    const growthRateChartData = chartData.prediction_years?.map(year => {
      const dataPoint = { year: year.toString() }
      Object.keys(growthRateData).forEach(sector => {
        if (growthRateData[sector][year] !== undefined) {
          dataPoint[sector] = growthRateData[sector][year]
        }
      })
      return dataPoint
    }) || []

    return { revenueChartData, profitChartData, profitMarginChartData, growthRateChartData }
  }

  // 图表颜色配置
  const chartColors = {
    '人药制剂板块': '#3b82f6',
    '人药原料板块': '#10b981',
    '植保板块': '#f59e0b',
    '动保板块': '#8b5cf6',
    '齐鲁制药集团': '#ef4444'
  }

  // 获取任务状态
  const getTaskStatus = (task) => {
    if (task.status === 'completed') {
      return { icon: CheckCircle, text: '已完成', color: 'text-green-600' }
    } else if (task.status === 'running') {
      return { icon: Clock, text: '运行中', color: 'text-blue-600' }
    } else if (task.status === 'failed') {
      return { icon: AlertCircle, text: '失败', color: 'text-red-600' }
    } else {
      return { icon: Clock, text: '等待中', color: 'text-gray-600' }
    }
  }

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div className="text-center space-y-2">
        <h1 className="text-3xl font-bold text-gray-900">报表结果</h1>
        <p className="text-gray-600">查看已完成任务的预测结果和AI分析报表</p>
      </div>

      {/* 任务列表 */}
      <div className="space-y-4">
        {loading ? (
          <div className="flex justify-center items-center py-8">
            <Loader2 className="h-8 w-8 animate-spin text-blue-600" />
            <span className="ml-2 text-gray-600">加载中...</span>
          </div>
        ) : tasks.length === 0 ? (
          <div className="text-center py-8 text-gray-500">
            暂无已完成的任务
          </div>
        ) : (
          Array.isArray(tasks) ? tasks
            .filter(task => task.status === 'completed')
            .map((task) => {
              const status = getTaskStatus(task)
              const StatusIcon = status.icon

              return (
                <Card key={task.id} className="hover:shadow-md transition-shadow">
                  <CardContent className="p-6">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center space-x-4">
                        <div className="flex-shrink-0">
                          <div className="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                            <Brain className="h-6 w-6 text-purple-600" />
                          </div>
                        </div>
                        <div className="flex-1 min-w-0">
                          <h3 className="text-lg font-semibold text-gray-900 truncate">
                            {task.task_name}
                          </h3>
                          <p className="text-sm text-gray-500">
                            完成时间: {formatDate(task.completed_at)}
                          </p>
                        </div>
                      </div>
                      <div className="flex items-center space-x-3">
                        <div className="flex items-center space-x-2">
                          <StatusIcon className={`h-4 w-4 ${status.color}`} />
                          <span className={`text-sm font-medium ${status.color}`}>
                            {status.text}
                          </span>
                        </div>
                        <Button
                          onClick={() => handleViewReport(task)}
                          className="bg-gray-800 hover:bg-gray-900 text-white"
                        >
                          <FileText className="h-4 w-4 mr-2" />
                          查看报表
                        </Button>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              )
            }) : (
              <div className="text-center py-8 text-red-500">
                任务数据格式错误
              </div>
            )
        )}
      </div>

      {/* 报表弹窗 */}
      {showReportModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4 overflow-hidden">
          <div className="bg-white rounded-lg shadow-xl w-full max-w-7xl h-[90vh] flex flex-col overflow-hidden">
            {/* 报表头部 */}
            <div className="relative p-6 border-b border-gray-200 flex-shrink-0">
              <div className="text-center">
                <h2 className="text-3xl font-bold text-gray-900 mb-2">
                  {selectedTask?.task_name}
                </h2>
                <p className="text-gray-600">
                  创建时间: {formatDate(selectedTask?.created_at)}
                </p>
              </div>
              <Button
                onClick={handleCloseReport}
                variant="ghost"
                size="sm"
                className="absolute top-6 right-6 text-gray-500 hover:text-gray-700"
              >
                <X className="h-5 w-5" />
              </Button>
            </div>

            {/* 报表内容 */}
            <div className="flex-1 overflow-y-auto p-6 min-h-0">
              {reportLoading ? (
                <div className="flex flex-col items-center justify-center py-12">
                  <Loader2 className="h-12 w-12 animate-spin text-blue-600 mb-4" />
                  <p className="text-lg text-gray-600">正在生成报表...</p>
                  <p className="text-sm text-gray-500 mt-2">请稍候，正在调用AI分析接口</p>
                </div>
              ) : (
                <div className="space-y-8">
                  {/* 历史数据表格 */}
                  {reportData?.historicalData && (
                    <div className="bg-white border border-gray-200 rounded-lg p-6">
                      <h3 className="text-xl font-semibold text-gray-800 mb-4 flex items-center">
                        <BarChart3 className="h-5 w-5 mr-2 text-blue-600" />
                        历史数据 (2021-2024年)
                      </h3>
                      <div className="overflow-x-auto">
                        <table className="w-full border-collapse border border-gray-300">
                          <thead>
                            <tr className="bg-blue-50">
                              <th className="border border-gray-300 px-4 py-3 text-left font-semibold text-gray-800">
                                单位
                              </th>
                              <th className="border border-gray-300 px-4 py-3 text-left font-semibold text-gray-800">
                                关键业绩指标
                              </th>
                              <th className="border border-gray-300 px-4 py-3 text-center font-semibold text-gray-800">
                                2021年
                              </th>
                              <th className="border border-gray-300 px-4 py-3 text-center font-semibold text-gray-800">
                                2022年
                              </th>
                              <th className="border border-gray-300 px-4 py-3 text-center font-semibold text-gray-800">
                                2023年
                              </th>
                              <th className="border border-gray-300 px-4 py-3 text-center font-semibold text-gray-800">
                                2024年
                              </th>
                            </tr>
                          </thead>
                          <tbody>
                            {reportData.historicalData.map((item, index) => (
                              <tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
                                <td className="border border-gray-300 px-4 py-3 font-medium text-gray-800">
                                  {item.unit}
                                </td>
                                <td className="border border-gray-300 px-4 py-3 text-gray-700">
                                  {item.indicator}
                                </td>
                                <td className="border border-gray-300 px-4 py-3 text-center text-gray-700">
                                  {item.year2021 || '-'}
                                </td>
                                <td className="border border-gray-300 px-4 py-3 text-center text-gray-700">
                                  {item.year2022 || '-'}
                                </td>
                                <td className="border border-gray-300 px-4 py-3 text-center text-gray-700">
                                  {item.year2023 || '-'}
                                </td>
                                <td className="border border-gray-300 px-4 py-3 text-center text-gray-700">
                                  {item.year2024 || '-'}
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    </div>
                  )}

                  {/* AI行业分析 */}
                  <div className="bg-white border border-gray-200 rounded-lg p-6">
                    <h3 className="text-xl font-semibold text-gray-800 mb-4 flex items-center">
                      <Brain className="h-5 w-5 mr-2 text-purple-600" />
                      AI行业分析
                      {aiLoading && <Loader2 className="h-4 w-4 ml-2 animate-spin text-purple-600" />}
                    </h3>
                    {aiLoading ? (
                      <div className="flex items-center justify-center py-8">
                        <Loader2 className="h-6 w-6 animate-spin text-purple-600 mr-2" />
                        <span className="text-gray-600">正在生成AI分析报告...</span>
                      </div>
                    ) : aiAnalysis ? (
                      <AIAnalysisDisplay analysisResult={aiAnalysis} />
                    ) : (
                      <div className="text-center py-8 text-gray-500">
                        暂无AI分析数据
                      </div>
                    )}
                  </div>

                  {/* 行业增长率和市场阶段CAGR */}
                  {reportData?.metasoOverview && reportData.metasoOverview.length > 0 && (
                    <div className="bg-white border border-gray-200 rounded-lg p-6">
                      <h3 className="text-xl font-semibold text-gray-800 mb-4 flex items-center">
                        <TrendingUp className="h-5 w-5 mr-2 text-blue-600" />
                        行业增长率预测参数
                      </h3>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        {reportData.metasoOverview.map((sector, index) => (
                          <div key={index} className="bg-gray-50 rounded-lg p-4">
                            <div className="flex items-center mb-3">
                              <div className={`w-10 h-10 rounded-full flex items-center justify-center mr-3 ${
                                index === 0 ? 'bg-blue-100' : 
                                index === 1 ? 'bg-green-100' : 
                                index === 2 ? 'bg-yellow-100' : 'bg-purple-100'
                              }`}>
                                <span className={`text-lg font-semibold ${
                                  index === 0 ? 'text-blue-600' : 
                                  index === 1 ? 'text-green-600' : 
                                  index === 2 ? 'text-yellow-600' : 'text-purple-600'
                                }`}>
                                  {sector.sector_name.charAt(0)}
                                </span>
                              </div>
                              <div>
                                <h4 className="font-semibold text-gray-800">{sector.sector_name}</h4>
                                <p className="text-sm text-gray-600">2025年08月27日 23:33</p>
                              </div>
                              <div className="ml-auto">
                                <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                  已完成
                                </span>
                              </div>
                            </div>
                            <div className="grid grid-cols-2 gap-4">
                              <div className="bg-blue-50 rounded p-3">
                                <p className="text-sm text-gray-600 mb-1">行业复合年增长率</p>
                                <p className="text-xl font-bold text-blue-600">
                                  {sector.industry_cagr ? `${sector.industry_cagr}%` : '0%'}
                                </p>
                              </div>
                              <div className="bg-green-50 rounded p-3">
                                <p className="text-sm text-gray-600 mb-1">市场阶段影响CAGR</p>
                                <p className="text-xl font-bold text-green-600">
                                  {sector.market_stage_cagr ? `${sector.market_stage_cagr}%` : '0%'}
                                </p>
                              </div>
                            </div>

                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* 图表展示区域 */}
                  {reportData?.chartData && (() => {
                    const { revenueChartData, profitChartData, profitMarginChartData, growthRateChartData } = processChartData(reportData.chartData)
                    
                    return (
                      <div className="space-y-8">
                        {/* 收入折线图 */}
                        <div className="bg-white border border-gray-200 rounded-lg p-6">
                          <h3 className="text-xl font-semibold text-gray-800 mb-4 flex items-center">
                            <TrendingUp className="h-5 w-5 mr-2 text-blue-600" />
                            销售收入趋势图 (2021-2030年)
                          </h3>
                          <div className="h-96">
                            <ResponsiveContainer width="100%" height="100%">
                              <LineChart data={revenueChartData}>
                                <CartesianGrid strokeDasharray="3 3" />
                                <XAxis dataKey="year" />
                                <YAxis label={{ value: '销售收入 (亿元)', angle: -90, position: 'insideLeft' }} />
                                <Tooltip formatter={(value) => [`${value} 亿元`, '销售收入']} />
                                <Legend />
                                {Object.keys(chartColors).map(sector => (
                                  <Line 
                                    key={sector}
                                    type="monotone" 
                                    dataKey={sector} 
                                    stroke={chartColors[sector]}
                                    strokeWidth={2}
                                    dot={{ fill: chartColors[sector], strokeWidth: 2, r: 4 }}
                                    connectNulls={false}
                                  />
                                ))}
                              </LineChart>
                            </ResponsiveContainer>
                          </div>
                        </div>

                        {/* 净利润折线图 */}
                        <div className="bg-white border border-gray-200 rounded-lg p-6">
                          <h3 className="text-xl font-semibold text-gray-800 mb-4 flex items-center">
                            <TrendingUp className="h-5 w-5 mr-2 text-green-600" />
                            净利润趋势图 (2021-2030年)
                          </h3>
                          <div className="h-96">
                            <ResponsiveContainer width="100%" height="100%">
                              <LineChart data={profitChartData}>
                                <CartesianGrid strokeDasharray="3 3" />
                                <XAxis dataKey="year" />
                                <YAxis label={{ value: '净利润 (亿元)', angle: -90, position: 'insideLeft' }} />
                                <Tooltip formatter={(value) => [`${value} 亿元`, '净利润']} />
                                <Legend />
                                {Object.keys(chartColors).map(sector => (
                                  <Line 
                                    key={sector}
                                    type="monotone" 
                                    dataKey={sector} 
                                    stroke={chartColors[sector]}
                                    strokeWidth={2}
                                    dot={{ fill: chartColors[sector], strokeWidth: 2, r: 4 }}
                                    connectNulls={false}
                                  />
                                ))}
                              </LineChart>
                            </ResponsiveContainer>
                          </div>
                        </div>



                        {/* 四大板块综合增长率方框展示 */}
                        {reportData?.chartData && reportData.chartData.growth_rate_data && (
                          <div className="bg-white border border-gray-200 rounded-lg p-6">
                            <h3 className="text-xl font-semibold text-gray-800 mb-4 flex items-center">
                              <TrendingUp className="h-5 w-5 mr-2 text-orange-600" />
                              四大板块综合增长率趋势 (2025-2030年)
                            </h3>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                              {Object.entries(reportData.chartData.growth_rate_data)
                                .filter(([sectorName]) => ['人药制剂板块', '人药原料板块', '植保板块', '动保板块'].includes(sectorName))
                                .map(([sectorName, yearData], index) => {
                                  // 计算平均增长率
                                  const rates = Object.values(yearData).filter(rate => rate !== undefined && rate !== null)
                                  const avgRate = rates.length > 0 ? (rates.reduce((sum, rate) => sum + rate, 0) / rates.length).toFixed(2) : '0.00'
                                  
                                  return (
                                    <div key={sectorName} className="bg-gray-50 rounded-lg p-4">
                                      <div className="flex items-center mb-3">
                                        <div className={`w-10 h-10 rounded-full flex items-center justify-center mr-3 ${
                                          index === 0 ? 'bg-blue-100' : 
                                          index === 1 ? 'bg-green-100' : 
                                          index === 2 ? 'bg-yellow-100' : 'bg-purple-100'
                                        }`}>
                                          <span className={`text-lg font-semibold ${
                                            index === 0 ? 'text-blue-600' : 
                                            index === 1 ? 'text-green-600' : 
                                            index === 2 ? 'text-yellow-600' : 'text-purple-600'
                                          }`}>
                                            {sectorName.charAt(0)}
                                          </span>
                                        </div>
                                        <div>
                                          <h4 className="font-semibold text-gray-800">{sectorName}</h4>
                                          <p className="text-sm text-gray-600">2025-2030年预测</p>
                                        </div>
                                        <div className="ml-auto">
                                          <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                            已完成
                                          </span>
                                        </div>
                                      </div>
                                      <div className="bg-orange-50 rounded p-3">
                                        <p className="text-sm text-gray-600 mb-1">平均综合增长率</p>
                                        <p className="text-2xl font-bold text-orange-600">
                                          {avgRate}%
                                        </p>
                                      </div>
                                      <div className="mt-3 grid grid-cols-3 gap-2 text-xs text-gray-500">
                                        {reportData.chartData.prediction_years?.slice(0, 6).map(year => (
                                          <div key={year} className="text-center">
                                            <div className="font-medium">{year}</div>
                                            <div>{yearData[year] ? `${yearData[year].toFixed(1)}%` : '-'}</div>
                                          </div>
                                        ))}
                                      </div>
                                    </div>
                                  )
                                })}
                            </div>
                          </div>
                        )}
                      </div>
                    )
                  })()}
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
